package user;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fasterxml.jackson.databind.ObjectMapper;
import util.DBUtil;

@WebServlet("/cartServlet")
public class userGetOwnCartServlet extends HttpServlet {
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String action = request.getParameter("action");

        if ("getOrders".equals(action)) {
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                response.getWriter().write(mapper.writeValueAsString(Map.of(
                    "status", "error",
                    "message", "未登录"
                )));
                return;
            }

            try (Connection conn = DBUtil.getConnection()) {
                int userId = (Integer) session.getAttribute("userId");
                List<Map<String, Object>> orders = getOrders(conn, userId);

                response.getWriter().write(mapper.writeValueAsString(Map.of(
                    "status", "success",
                    "orders", orders
                )));
            } catch (SQLException e) {
                e.printStackTrace();
                response.getWriter().write(mapper.writeValueAsString(Map.of(
                    "status", "error",
                    "message", "获取订单失败：" + e.getMessage()
                )));
            }
        }
    }

    private List<Map<String, Object>> getOrders(Connection conn, int userId) throws SQLException {
        List<Map<String, Object>> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC";

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Map<String, Object> order = new HashMap<>();
                    order.put("id", rs.getInt("id"));
                    order.put("productName", rs.getString("product_name"));
                    order.put("total", rs.getBigDecimal("total"));
                    order.put("status", rs.getString("status"));
                    order.put("createdAt", rs.getTimestamp("created_at"));
                    orders.add(order);
                }
            }
        }
        return orders;
    }
}